<template>
  <!-- viewer.properties: 该文件已放置本地，使用相对路径引入，亦可放置cdn上，使用网络路径引入 -->
  <link rel="resource" type="application/l10n" href="/src/assets/files/viewer.properties">
  <VuePdfApp 
    :page-scale="pageScale"
    :theme="theme"
    :style="`width: ${viewerWidth}; height: ${viewerHeight};`"
    :pdf="src"
    :fileName="fileName"
    @pages-rendered="pagesRendered"
    v-bind="$attrs"
    @keydown="handleKeyDown"></VuePdfApp>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import VuePdfApp from 'vue3-pdf-app'
import 'vue3-pdf-app/dist/icons/main.css'
interface Props {
  src: string|ArrayBuffer // pdf地址
  width?: string|number // 预览容器宽度
  height?: string|number // 预览容器高度
  pageScale?: number|string // 页面默认缩放规则，可选 'page-actual'|'page-width'|'page-height'|'page-fit'|'auto'
  theme?: string // 预览主题 可选 dark | light
  fileName?: string // 覆盖pdf文件名
}
const props = withDefaults(defineProps<Props>(), {
  src: '',
  width: '100%',
  height: '100vh',
  pageScale: 'page-fit', // 默认自适应展示一页
  theme: 'dark',
  fileName: ''
})
const viewerWidth = computed(() => {
  if (typeof props.width === 'number') {
    return props.width + 'px'
  } else {
    return props.width
  }
})
const viewerHeight = computed(() => {
  if (typeof props.height === 'number') {
    return props.height + 'px'
  } else {
    return props.height
  }
})
// emitted only once when Pdfjs library is binded to vue component
// Can be used to set Pdfjs config before pdf document opening.
// function afterCreated (pdfApp: any) {
//   console.log('afterCreated pdfApp:', pdfApp)
// }
// emitted when pdf is opened but pages are not rendered
// function openHandler (pdfApp: any) {
//   console.log('open pdfApp:', pdfApp)
// }
const emit = defineEmits(['loaded'])
// emitted when pdf document pages are rendered. Can be used to set default pages scale
function pagesRendered (pdfApp: any) {
  console.log('pagesRendered pdfApp:', pdfApp)
  emit('loaded', pdfApp)
}
const handleKeyDown = (event:any) => {
    if (event.keyCode === 32 || event.keyCode === 8) {
        // 阻止默认行为
        event.preventDefault();
        console.log(event)
    }
}
</script>

<style scoped>
#pdf {
  pointer-events: none;
}
</style>